<template>
  <div>
    <Row class="list_row" style="margin-top: 0px;min-height: 400px;">
      <Row style="margin: 5px 0px 10px 0px;">
        <Select v-model="selTrainCenterId" filterable  :placeholder="$t('common.trainSePlaceTips')" style="width: 200px;margin-right: 20px"
                v-show="isCanChooseTc">
          <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{ tc.name }}</Option>
        </Select>
        <Input v-model="searchKeyword"  :placeholder="$t('deviceP.phoneOrStudentTips')"  style="width: 200px;margin-right: 20px"/>
        <Button class="btnWhite" type="primary" icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
      </Row>
      <Table :columns="trainerColumn" border :data="dataList" stripe :no-data-text="noDataMsg">
        <template slot-scope="{ row, index }" slot="seq">
          {{ (currentPage - 1) * pageSize + index + 1 }}
        </template>
        <template slot-scope="{ row, index }" slot="status">
          <Icon v-if="row.status == 0" custom="iconfont icon-device" size="24" color="#aaaaaa"/>
          <Icon v-else custom="iconfont icon-device" size="24" color="#2d8cf0"/>
        </template>
      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>

    <!-- 运动记录弹窗 -->
    <Modal v-model="sportsRecordModelVisiable" :mask-closable="false" width="100" :title="modalTitle" :fullscreen="true"
           :scrollable="true">
      <div>
        <Tabs :value="selTab">
          <!-- 1.计划运动 -->
          <TabPane name="planSports" :label="$t('common.planS')">
            <Row class="list_row" style="margin-top: 0px">
              <Row style="margin: 5px 0px 10px 0px;">
                <Date-picker format="yyyy-MM-dd" type="date" v-model="startQueryDate" placement="bottom-end"
                :placeholder="$t('common.startTimePlaceTips')" clearable style="width: 200px"
                             @on-change="startDateChange"></Date-picker>
                <span style="margin-left: 10px;margin-right: 10px;">-</span>
                <Date-picker format="yyyy-MM-dd" type="date" v-model="endQueryDate" placement="bottom-end"
                :placeholder="$t('common.endTimePlaceTips')"  clearable style="width: 200px"
                             @on-change="endDateChange"></Date-picker>
                <Button type="primary" icon="ios-search" style="margin-left: 20px" @click="searchSportsRecords">{{$t('search')}}
                </Button>
                <Button icon="md-refresh" style="margin-left: 20px" @click="reset(true)">{{$t('reset')}}</Button>
                <Button type="warning" icon="ios-download" style="margin-left: 20px" :loading="exportLoading" @click="handleExport">{{$t('export')}}
                </Button>
              </Row>
              <Table :columns="sportsRecordColumn" border :data="sportsRecordDataArr" stripe style="min-height: 278px;">
                <template slot-scope="{ row, index }" slot="seq">
                  {{ (sportsRecordCurrentPage - 1) * sportsRecordCountPageSize + index + 1 }}
                </template>
              </Table>
              <div class="div_page">
                <Page :total="sportsRecordTotalCount" :current="sportsRecordCurrentPage"
                      :page-size="sportsRecordCountPageSize"
                      show-total show-elevator prev-text="<" next-text=">" @on-change="sportsRecordPageChg"/>
              </div>
            </Row>
          </TabPane>
          <!-- 2.全局配置项 -->
          <TabPane name="freeTrain" :label="$t('common.actuoE')">
            <free-sport ref="freeSports" :trainer-id="selTrainerId" :trainCenterId="selTrainCenterId"></free-sport>
          </TabPane>
        </Tabs>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="reset(false)">{{$t('cancel')}}</Button>
      </div>
       <div slot="close" style="text-align: center">
        <i class="ivu-icon ivu-icon-ios-close" @click="reset(false)" ></i>
      </div>
    </Modal>

  </div>
</template>
<script>
import TrainCenterApi from '@/api/trainCenterApi'
import TrainerApi from '@/api/trainerApi'
import AnalysisReportApi from '@/api/analysisReportApi'
import SportsRecordExpendRow from './SportsRecordExpend.vue'
import FreeSport from './freeSport.vue'

import { isEmpty } from '@/libs/util'

export default {
  components: {
    FreeSport
  },
  data () {
    return {
      // 导出按钮遮罩层
      exportLoading: false,
      selTab: 'planSports',
      saveLoading: false,
      searchKeyword: '',
      noDataMsg:  this.$t('common.noData'),
      isCanChooseTc: false,
      selTrainCenterId: '',
      trainCenterList: [],
      entityModelVisiable: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      trainerColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title: this.$t('common.trainerName'), 
          key: 'nickName'
        },
        {
          title: this.$i18n.locale === 'zh-CN' ? this.$t('common.phone') : this.$t('common.mail'), 
          key: this.$i18n.locale === 'zh-CN' ? "phone" : "mail",
        },
        {
          title: this.$t('cocach'), 
          key: 'coachNames'
        },
        {
          title: this.$t('trainerP.createTime'),
          key: 'createTime'
        },
        {
          title: this.$t('common.optColumn') ,
          key: 'action',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnYellow',
                on: {
                  click: () => {
                    this.showSportsRecordModal(params.row.id, params.row.nickName)
                  }
                }
              },  this.$t('common.srecord'))
            ])
          }
        }],
      modalTitle: '',
      startQueryDate: '',
      endQueryDate: '',
      startQueryDateVal: '',
      endQueryDateVal: '',
      selTrainerId: '',
      sportsRecordDataArr: [],
      sportsRecordTotalCount: 0,
      sportsRecordCurrentPage: 1,
      sportsRecordCountPageSize: 10,
      sportsRecordModelVisiable: false,
      sportsRecordColumn: [
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(SportsRecordExpendRow, {
              props: {
                row: params.row
              }
            })
          }
        },
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title: this.$t('common.planName'), 
          key: 'planName'
        },
        {
          title: this.$t('common.courseName'), 
          key: 'courseName'
        },
        {
          title: this.$t('common.trainActionColumn'), 
          key: 'actionName'
        },
        {
          title: this.$t('common.sportStartColumn'), 
          key: 'startTrainTime'
        },
        {
          title: this.$t('common.sportEndColumn') , 
          key: 'endTrainTime'
        },
        {
          title: this.$t('common.optColumn') ,
          key: 'action',
          width: 150,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnBlue',
                on: {
                  click: () => {
                    this.viewTotalAnalysis(params.row)
                  }
                }
              },  this.$t('common.analysisBtn'))
            ])
          }
        }
      ]
    }
  },
  watch: {
    'selTrainCenterId':
      function (val) {
        this.fetchDataList()
      }
  },
  created () {
    this.initFunc()
  },
  methods: {
    initFunc () {
      TrainCenterApi.userTrainCenterScope().then(res => {
        const data = res.data.data
        if (data.canSelect == '1') {
          this.isCanChooseTc = true
          this.trainCenterList = data.list
          if (this.trainCenterList.length > 0) {
            this.selTrainCenterId = this.trainCenterList[0].id
            
          }
        } else {
          this.selTrainCenterId = data.trainCenterId
        }
        this.search()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    search () {
      this.currentPage = 1
      this.fetchDataList()
    },
    fetchDataList () {
      if (isEmpty(this.selTrainCenterId)) {
        this.$Message.error(this.$t('common.trainSePlaceTips'));
        return
      }
      this.noDataMsg = this.$t('common.loading');
      this.dataList = []
      var param = {
        'pageSize': this.pageSize,
        'currentPage': this.currentPage,
        'trainCenterId': this.selTrainCenterId
      }
      if (this.searchKeyword.length > 0) {
        param.nickName = this.searchKeyword
      }
      TrainerApi.pageResult(param).then(res => {
        
        this.dataList = res.data.data.pageResult.items
        
        this.totalCount = res.data.data.pageResult.totalCount
        this.noDataMsg = this.$t('common.noData')
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchDataList()
    },
    showSportsRecordModal (id, nickName) {
      this.modalTitle =  this.$t('common.srecord') + '——' + nickName 
      this.selTrainerId = id
      this.sportsRecordModelVisiable = true
      this.sportsRecordCurrentPage = 1
      this.searchSportsRecords()
      this.$refs.freeSports.initData(this.selTrainCenterId, this.selTrainerId)
    },
    searchSportsRecords () {
      this.sportsRecordDataArr = []
      var param = {
        'currentPage': this.sportsRecordCurrentPage,
        'pageSize': this.sportsRecordCountPageSize,
        'trainerId': this.selTrainerId,
        'trainCenterId': this.selTrainCenterId
      }
      
      if (this.startQueryDateVal.length > 0) {
        param.startQueryDate = this.startQueryDateVal
      }
      if (this.endQueryDateVal.length > 0) {
        param.endQueryDate = this.endQueryDateVal
      }
      AnalysisReportApi.trainDetailSportsRecord(param).then(res => {
        this.sportsRecordDataArr = res.data.data.items
        this.sportsRecordTotalCount = res.data.data.totalCount
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    sportsRecordPageChg (selPage) {
      this.sportsRecordCurrentPage = selPage
      this.searchSportsRecords()
    },
    startDateChange (formatTime) {
      this.startQueryDateVal = formatTime
    },
    endDateChange (formatTime) {
      this.endQueryDateVal = formatTime
    },
    // 重置查询
    reset (isOpen) {
      this.sportsRecordModelVisiable = isOpen
      this.startQueryDate = ''
      this.startQueryDateVal = ''
      this.endQueryDate = ''
      this.endQueryDateVal = ''
      if (!isOpen) {
        this.$refs.freeSports.startQueryDate = ''
        this.$refs.freeSports.startQueryDateVal = ''
        this.$refs.freeSports.endQueryDate = ''
        this.$refs.freeSports.endQueryDateVal = ''
      } else {
        this.searchSportsRecords()
      }
    },
    // 汇总分析
    viewTotalAnalysis (row) {
      const routeData = this.$router.resolve({
        name: 'trainDetailReport',
        query: { day: row.day, trainDetailId: row.trainDetailId, trainerId: row.trainerId }
      })
      window.open(routeData.href, '_blank')
    },
    /** 导出按钮操作 */
    handleExport () {
      // 先刷新页面查询结果
      this.searchSportsRecords()
      this.$Modal.confirm({
        title:  this.$t('common.exportPromt'),
        content: this.$t('common.exportQ')+"</br>"+this.$t('common.eq1')+"<span style='color:red'>"+ this.$t('common.eq2') +"</span>，"+ this.$t('common.eq3')+"<span style='color:red'>"+this.$t('common.eq4')+"</span>，" + this.$t('common.eq5') ,
        okText: this.$t('yes'),
        cancelText: this.$t('cancel'),
        onOk: () => {
          this.exportLoading = true
          this.exportExcel().then(response => {
            var timestamp = new Date().toLocaleDateString()
            let blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
            let fileName = this.$t('common.plansRecord') + timestamp
            const link = document.createElement('a')
            link.download = fileName
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
            this.exportLoading = false
          }).catch(() => { this.exportLoading = false })
        }
      })
    },
    exportExcel () {
      var param = {
        'trainerId': this.selTrainerId,
        'trainCenterId': this.selTrainCenterId
      }
      if (this.startQueryDateVal.length > 0) {
        param.startQueryDate = this.startQueryDateVal
      }
      if (this.endQueryDateVal.length > 0) {
        param.endQueryDate = this.endQueryDateVal
      }
      return AnalysisReportApi.exportTrainRecordExcel(param)
    }
  }
}
</script>
